<template>
  <div class="main-content">
    <el-row>
      <el-col>
        <!-- 搜索栏 -->
        <el-form
          v-show="showSearch"
          ref="queryRef"
          :model="queryParams"
          :inline="true"
          class="search-form bg-bg_color w-full pl-8 pt-[12px] overflow-auto"
        >
          <el-form-item label="分类名称：" prop="categoryName">
            <el-input
              v-model="queryParams.categoryName"
              placeholder="请输入分类名称"
              clearable
              class="w-[200px]!"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="是否显示" prop="is_displayed">
            <el-select
              v-model="queryParams.is_displayed"
              placeholder="请选择是否显示"
              clearable
              class="w-[200px]!"
            >
              <el-option label="是" :value="true" />
              <el-option label="否" :value="false" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :icon="useRenderIcon(Search)" :loading="loading" @click="handleQuery">
              搜索
            </el-button>
            <el-button :icon="useRenderIcon(Refresh)" @click="resetQuery"> 重置 </el-button>
          </el-form-item>
        </el-form>

        <!-- 表格 -->
        <PureTableBar title="商品分类管理" :columns="columns" @refresh="fetchCategories">
          <template #buttons>
            <el-button type="primary" :icon="useRenderIcon(AddFill)" @click="showAddCategoryDialog">
              新增分类
            </el-button>
            <el-select
              v-model="expandLevel"
              placeholder="展开层级"
              style="width: 140px; margin-left: 12px"
              @change="handleExpandLevelChange"
            >
              <el-option label="全部折叠" :value="0" />
              <el-option label="展开1层" :value="1" />
              <el-option label="展开2层" :value="2" />
              <el-option label="展开3层" :value="3" />
              <el-option label="展开4层" :value="4" />
              <el-option label="全部展开" :value="-1" />
            </el-select>
          </template>

          <template v-slot="{ size, dynamicColumns }">
            <pure-table
              ref="cateTableRef"
              align-whole="center"
              row-key="id"
              :loading="loading"
              :size="size"
              :data="cateTree"
              :columns="dynamicColumns"
              :tree-props="{
                children: 'children',
                hasChildren: 'hasChildren',
                checkStrictly: false
              }"
              :indent="32"
              :pagination="pagination"
              :header-cell-style="{
                background: 'var(--el-fill-color-light)',
                color: 'var(--el-text-color-primary)'
              }"
              @page-size-change="handleSizeChange"
              @page-current-change="handleCurrentChange"
            />
          </template>
        </PureTableBar>
      </el-col>
    </el-row>

    <!-- 添加或修改分类对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600">
      <el-form :model="form" label-width="100px">
        <el-form-item label="分类名称" required>
          <el-input v-model="form.name" placeholder="请输入（限60字）" maxlength="60" />
        </el-form-item>
        <el-form-item label="上级分类" required>
          <el-tree-select
            v-model="form.parent_id"
            :data="cateTreeForSelect"
            :props="{ value: 'id', label: 'name' }"
            check-strictly
            :render-after-expand="false"
            placeholder="请选择商品分类"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="form.sort_order" :min="0" />
        </el-form-item>
        <el-form-item label="是否显示">
          <el-switch v-model="form.is_displayed" />
        </el-form-item>
        <el-form-item>
          <img v-if="form.image" :src="form.image" class="avatar" alt="头像" />
        </el-form-item>
        <el-form-item label="分类图标">
          <el-upload
            class="upload-demo"
            action="http://127.0.0.1:5050/system/upload-file"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
          <el-input v-model="form.image" clearable placeholder="请输入分类图标URL" />
        </el-form-item>
        <el-form-item>
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, nextTick, watch, h } from "vue";
import { ElMessage, ElMessageBox, ElImage, ElButton, ElTag } from "element-plus";
import { getCateList, addCate, updateCate, delCate } from "@/api/good-cate";
import { PureTableBar } from "@/components/RePureTableBar";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";

// 引入图标
import AddFill from "~icons/ri/add-circle-line";
import Delete from "~icons/ep/delete";
import EditPen from "~icons/ep/edit-pen";
import Refresh from "~icons/ep/refresh";
import Search from "~icons/ri/search-line";
import Plus from "~icons/ep/plus";
import Edit from "~icons/ep/edit";

defineOptions({
  name: "GoodsCategoryManagement"
});

const queryParams = reactive({
  categoryName: "",
  page: 1,
  pageSize: 10,
  is_displayed: null
});
const showSearch = ref(true);
const loading = ref(false);
const cateTree = ref([]);
const cateTableRef = ref();
const expandLevel = ref(1);
const dialogVisible = ref(false);

// 分页配置
const pagination = reactive({
  total: 0,
  pageSize: 10,
  currentPage: 1,
  background: true,
  pageSizes: [10, 20, 30, 50, 100]
});

const form = reactive({
  id: undefined,
  name: "",
  parent_id: 0,
  sort_order: 0,
  is_displayed: true,
  image: ""
});

const dialogTitle = computed(() => (form.id ? "修改分类" : "新增分类"));

const cateTreeForSelect = computed(() => {
  return [...cateTree.value];
});

// 编辑分类
const editCategory = row => {
  form.id = row.id;
  form.name = row.name;
  form.parent_id = row.parent_id ?? 0;
  form.sort_order = row.sort_order;
  form.is_displayed = row.is_displayed;
  form.image = row.image;
  dialogVisible.value = true;
};

// 新增下级分类
const handleAddSubCategory = row => {
  Object.assign(form, {
    id: undefined,
    name: "",
    parent_id: row.id,
    sort_order: 0,
    is_displayed: true,
    image: ""
  });
  dialogVisible.value = true;
};

// 删除分类
const handleDeleteCategory = async row => {
  try {
    await ElMessageBox.confirm("此操作将删除该分类，是否继续？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    });
    await delCate({ id: row.id });
    ElMessage.success("删除成功");
    await fetchCategories();
  } catch {
    /* 取消 */
  }
};

// 表格列配置
const columns: TableColumnList = [
  {
    label: "分类编号",
    prop: "id",
    width: 180,
    align: "center"
  },
  {
    label: "分类名称",
    prop: "name",
    width: 120,
    align: "center"
  },
  {
    label: "排序",
    prop: "sort_order",
    width: 80,
    align: "center"
  },
  {
    label: "分类图标",
    prop: "image",
    align: "center",
    cellRenderer: ({ row }) => {
      if (row.image) {
        return h(ElImage, {
          src: row.image,
          alt: "分类图标",
          class: "h-[80px]",
          previewSrcList: [row.image],
          previewTeleported: true,
          hideOnClickModal: true,
          fit: "cover",
          scale: 0.8
        });
      }
      return h("span", { class: "text-gray-400" }, "无");
    }
  },
  {
    label: "是否显示",
    prop: "is_displayed",
    align: "center",
    cellRenderer: ({ row }) => {
      return h(
        ElTag,
        {
          type: row.is_displayed ? "success" : "info",
          size: "small"
        },
        () => (row.is_displayed ? "是" : "否")
      );
    }
  },
  {
    label: "操作",
    fixed: "right",
    width: 400,
    align: "center",
    cellRenderer: data => {
      const { row } = data;
      const { props } = data as any;
      return h("div", { class: "flex gap-2 justify-center" }, [
        h(
          ElButton,
          {
            link: true,
            type: "primary",
            size: props?.size,
            icon: useRenderIcon(EditPen),
            onClick: () => editCategory(row)
          },
          { default: () => "编辑" }
        ),
        h(
          ElButton,
          {
            link: true,
            type: "primary",
            size: props?.size,
            icon: useRenderIcon(Plus),
            onClick: () => handleAddSubCategory(row)
          },
          { default: () => "新增下级" }
        ),
        h(
          ElButton,
          {
            link: true,
            type: "danger",
            size: props?.size,
            icon: useRenderIcon(Delete),
            onClick: () => handleDeleteCategory(row)
          },
          { default: () => "删除" }
        )
      ]);
    }
  }
];

// 获取分类列表
const fetchCategories = async () => {
  try {
    loading.value = true;
    const params = {
      categoryName: queryParams.categoryName,
      is_displayed: queryParams.is_displayed,
      page: pagination.currentPage,
      pageSize: pagination.pageSize
    };
    const { code, data, message } = await getCateList(params);
    if (code !== 200) {
      ElMessage.error(message);
      return;
    }
    cateTree.value = data?.list || data || [];
    pagination.total = data?.pagination?.total || 0;
    console.log("cateTree", cateTree.value);
  } catch (e) {
    ElMessage.error("获取分类失败");
  } finally {
    loading.value = false;
  }
};

// 分页-每页条数改变
const handleSizeChange = (val: number) => {
  pagination.pageSize = val;
  pagination.currentPage = 1;
  fetchCategories();
};

// 分页-当前页改变
const handleCurrentChange = (val: number) => {
  pagination.currentPage = val;
  fetchCategories();
};

// 查询搜索
const handleQuery = () => {
  pagination.currentPage = 1;
  fetchCategories();
};
// 重置搜索
const resetQuery = () => {
  queryParams.categoryName = "";
  queryParams.is_displayed = null;
  pagination.currentPage = 1;
  fetchCategories();
};
// 展示新增分类对话框
const showAddCategoryDialog = () => {
  Object.assign(form, {
    id: undefined,
    name: "",
    parent_id: 0,
    sort_order: 0,
    is_displayed: true,
    image: ""
  });
  dialogVisible.value = true;
};

// 提交表单
const submitForm = async () => {
  try {
    if (form.id) {
      await updateCate(form);
      ElMessage.success("修改成功");
    } else {
      await addCate(form);
      ElMessage.success("新增成功");
    }
    dialogVisible.value = false;
    await fetchCategories();
  } catch (e) {
    ElMessage.error("操作失败：" + e.message);
  }
};

const handleExpandLevelChange = level => {
  // pure-table 组件内部有 getTableRef 方法获取真实的 el-table 实例
  const pureTableInstance = cateTableRef.value;
  console.log("PureTable 实例:", pureTableInstance);

  if (!pureTableInstance) {
    console.warn("PureTable 实例未找到");
    return;
  }

  // 尝试获取内部的 el-table 实例
  const table = pureTableInstance.getTableRef?.() || pureTableInstance;
  console.log("展开层级变化:", level, "El-Table 实例:", table);

  if (!table || !table.toggleRowExpansion) {
    console.warn("El-Table 实例或 toggleRowExpansion 方法未找到");
    return;
  }

  const expand = (rows, level) => {
    rows.forEach(row => {
      if (level > 0) {
        table.toggleRowExpansion(row, true);
        if (row.children && row.children.length) {
          expand(row.children, level - 1);
        }
      } else {
        table.toggleRowExpansion(row, false);
      }
    });
  };

  const collapseAll = rows => {
    rows.forEach(row => {
      table.toggleRowExpansion(row, false);
      if (row.children && row.children.length) {
        collapseAll(row.children);
      }
    });
  };

  const expandAll = rows => {
    rows.forEach(row => {
      table.toggleRowExpansion(row, true);
      if (row.children && row.children.length) {
        expandAll(row.children);
      }
    });
  };

  if (level === 0) {
    collapseAll(cateTree.value);
  } else if (level === -1) {
    expandAll(cateTree.value);
  } else {
    collapseAll(cateTree.value);
    expand(cateTree.value, level);
  }
};

const handleUploadSuccess = (res: any) => {
  form.image = import.meta.env.VITE_BASE_URL + res.data.url;
  console.log("form.image", res.data.url);
};
watch(
  [cateTree, expandLevel], // 同时监听“树数据”和“展开层级”
  ([tree, level]) => {
    if (tree.length) {
      // 数据已经有了
      nextTick(() => handleExpandLevelChange(level));
    }
  },
  { immediate: true }
);
onMounted(() => {
  fetchCategories();
});
</script>

<style lang="scss" scoped>
.main-content {
  margin: 24px 24px 10px !important;
}

.search-form {
  :deep(.el-form-item) {
    margin-bottom: 12px;
  }
}

.avatar {
  display: block;
  width: 280px;
  height: 178px;
  margin-top: 10px;
}
</style>
